package com.putao.album.tag;

import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.tag.adapter.TagAlbumPhotoAddAdapter;
import com.putao.album.tag.bean.TagAlbumPhotoItem;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;
import com.putao.album.util.UmengTouchEvent;
import com.putao.album.widget.stickygridheaders.StickyGridHeadersGridView;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by jidongdong on 15/4/29.
 * <p/>
 * 批量往该标签相册中添加照片
 */
public class ActivityTagAlbumPhotoAdd extends BaseActivity {
    private Button btn_add, back_btn;
    private TextView title_tv;
    private StickyGridHeadersGridView mGridView;
    private List<TagAlbumPhotoItem> mDataList = new ArrayList<TagAlbumPhotoItem>();
    private String mTagName;
    private String mTagId;
    private int mSelectnum = 0;
    private TagAlbumPhotoAddAdapter mTagAlbumPhotoAddAdapter;
    private String nextPage = "1";
    private boolean mIsLastPage = false;
    private boolean mIsRefreshing = false;
    private String mBabyID;

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_tag_album_photo_add;
    }

    @Override
    public void doInitSubViews(View view) {
        btn_add = queryViewById(R.id.btn_add, true);
        back_btn = queryViewById(R.id.back_btn, true);
        back_btn.setBackgroundResource(R.drawable.all_button_close);
        queryViewById(R.id.right_btn).setVisibility(View.GONE);
        setPageTitle();
        mGridView = queryViewById(R.id.asset_grid);
        mGridView.setOnItemClickListener(mOnItemClickListener);
        mGridView.setHeadersIgnorePadding(true);
        mGridView.setOnScrollListener(mGridViewScrollListener);
    }

    AbsListView.OnScrollListener mGridViewScrollListener = new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            switch (scrollState) {
                case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                    // 判断滚动到底部
                    if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                        updateData();
                    }
                    break;
                case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                    break;
                case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                    break;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        }
    };


    /**
     * 单击
     */
    AdapterView.OnItemClickListener mOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            boolean selected = mDataList.get(position).selected;
            mDataList.get(position).selected = !selected;
            if (!selected) {
                mSelectnum++;
            } else {
                if (mSelectnum > 0)
                    mSelectnum--;
                else {
                    mSelectnum = 0;
                }
            }
            setSelectNumText();
            mTagAlbumPhotoAddAdapter.notifyDataSetChanged();
        }
    };


    @Override
    public void doInitData() {
        mBabyID = CommonUtils.getBabyId();
        setUpData();
        mTagAlbumPhotoAddAdapter = new TagAlbumPhotoAddAdapter(mContext, mDataList, mGridView);
        mTagAlbumPhotoAddAdapter.setOnHeaderSelectButtonClickedListener(new TagAlbumPhotoAddAdapter.OnHeaderSelectButtonClickedListener() {
            @Override
            public void onClick(View v) {
                String group = (String) v.getTag();
                if (group != null) {
                    updateDataList(group);
                }
            }
        });
        mGridView.setAdapter(mTagAlbumPhotoAddAdapter);
    }

    void updateDataList(String group) {
        for (int i = 0; i < mDataList.size(); i++) {
            if (mDataList.get(i).section == Integer.valueOf(group)) {
                TagAlbumPhotoItem item = mDataList.get(i);

                if (item.section_selected) {//已经全选
                    if (item.selected && item.canAddTag) {
                        mSelectnum--;
                        mDataList.get(i).selected = false;
                    }
                    mDataList.get(i).section_selected = false;
                } else {
                    if (!item.selected && item.canAddTag) {
                        mSelectnum++;
                        mDataList.get(i).selected = true;
                    }
                    mDataList.get(i).section_selected = true;
                }
            }
        }
        setSelectNumText();
        mTagAlbumPhotoAddAdapter.notifyDataSetChanged();
    }


    void setUpData() {
        updateData();
    }

    protected void updateData() {

        if (mIsLastPage || mIsRefreshing) {
            return;
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("page", nextPage);
        params.put("baby_id", mBabyID);
        params.put("tag_id", mTagId);
        params.put("tag", mTagName);
        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_GET_BABY_PHOTO_LIST, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    Loger.d(response);
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        doAnalyzeDataList(HttpRequestUtil.getResponseData(response));
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
        mIsRefreshing = true;

    }

    /**
     * 解析返回的标签相册列表数据
     *
     * @param data
     */
    void doAnalyzeDataList(JSONObject data) {
        JSONArray list = data.optJSONArray("list");
        if (list != null) {
            for (int i = 0; i < list.length(); i++) {
                JSONObject o = null;
                try {
                    o = list.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (o != null) {
                    int group = o.optInt("group");
                    String albumName = o.optString("albumName");
                    JSONArray photoarray = null;
                    try {
                        photoarray = o.getJSONArray("albunPicItem");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    doBabyPhotoListWrapper(group, albumName, photoarray);
                }
            }
            mTagAlbumPhotoAddAdapter.notifyDataSetChanged();
        }
        nextPage = data.optString("nextPage");
        mIsRefreshing = false;
        if (nextPage.equals("-1")) {
            mIsLastPage = true;
        }
    }

    /**
     * 解析分组照片列表
     *
     * @param group
     * @param albumName
     * @param photoarray
     */
    private void doBabyPhotoListWrapper(int group, String albumName, JSONArray photoarray) {
        if (photoarray != null) {
            for (int j = 0; j < photoarray.length(); j++) {
                JSONObject obj = null;
                try {
                    obj = photoarray.getJSONObject(j);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (obj != null) {
                    String id = obj.optString("id");
                    String picUrl = obj.optString("picUrl");
                    String is_selected = obj.optString("is_selected");
                    TagAlbumPhotoItem item = new TagAlbumPhotoItem();
                    item.image_id = id;
                    item.image_url = picUrl;
                    item.photo_datetime = albumName;
                    item.section = group;
                    item.canAddTag = is_selected.equals("1");
                    mDataList.add(item);
                }
            }
        }
    }

    void doAddPhotoTagBat() {
        final JSONArray photos = new JSONArray();
        for (int i = 0; i < mDataList.size(); i++) {
            if (mDataList.get(i).selected == true) {
                photos.put(mDataList.get(i).image_id);
            }
        }

        if (photos.length() == 0) {
            showToast("您还没有选择照片哦");
            return;
        }
        MobclickAgent.onEvent(mContext, UmengTouchEvent.ADD_LABELPHOTO);

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_ids", photos.toString());
        params.put("tag_id", mTagId);
        params.put("tag", mTagName);
        params.put("baby_id", mBabyID);
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_BATCH_ADD_PHOTO_TAG, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true, new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        showToast("添加成功");
                        JSONObject data = HttpRequestUtil.getResponseData(response);
                        String cover = "";
                        if (data != null) {
                            cover = data.optString("cover");
                        }
                        sendUpdateAlbumEvent(photos.length(), cover);
                        finish();
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
        mIsRefreshing = true;
    }

    private void sendUpdateAlbumEvent(int photos, String cover) {
        Bundle bundle = new Bundle();
        bundle.putString("tag_name", mTagName);
        bundle.putInt("type", 0);
        bundle.putInt("count", photos);
        bundle.putString("cover", cover);
        EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_BATCH_ADD_TAG_PHOTO, bundle));
    }


    /**
     * 设置选则的数量
     */
    void setSelectNumText() {
        btn_add.setText("添加标签\"" + mTagName + "\"  " + mSelectnum + " ");
    }

    void setPageTitle() {
        title_tv = queryViewById(R.id.title_tv);
        if (getIntent() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mTagName = bundle.getString("tag_name", "");
                mTagId = bundle.getString("tag_id");
                setSelectNumText();
            }
        }
        title_tv.setText(R.string.page_title_tag_add_bat);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.btn_add:
                doAddPhotoTagBat();
                break;
        }
    }
}
